package com.pet_clinic.controller;

import com.atguigu.campus.pojo.Admin;
import com.atguigu.campus.pojo.LogionForm;
import com.atguigu.campus.pojo.Student;
import com.atguigu.campus.pojo.Teacher;
import com.atguigu.campus.service.AdminService;
import com.atguigu.campus.service.StudentService;
import com.atguigu.campus.service.TeacherService;
import com.atguigu.campus.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Resource
    private AdminService adminService;

    @Resource
    private StudentService studentService;

    @Resource
    private TeacherService teacherService;

    @RequestMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpSession session, HttpServletResponse response) throws IOException {
        //通过工具类CreateVerifiCodeImage 获得验证码图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        //获取验证码图片中的值 并保存在session域中 用于用于登录时校验
        String code = new String(CreateVerifiCodeImage.getVerifiCode());
        //将验证码的值保存到session中，用于登录校验
        session.setAttribute("code", code);
        //将获取到的验证码图片响应到浏览器
        ImageIO.write(verifiCodeImage, "JPG", response.getOutputStream());
    }

    /**
     * 登录功能 进行验证码校验以及用户名密码校验
     * 登录成功时 生成token返回给浏览器
     * @param logionForm 生成的登录信息表单
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<Object> login(@RequestBody LogionForm logionForm,HttpSession session){
        //先获取session域中的验证码值
        String code = (String) session.getAttribute("code");
        if(code == null|| code.isEmpty()){
            return Result.fail().message("验证码失效，请重新输入验证码");
        }
        //获取用户输入的验证码
        String userInputCode=logionForm.getVerifiCode();
        if(!userInputCode.equalsIgnoreCase(code)){
            return Result.fail().message("验证码错误");
        }

        //销毁session域中的验证码值
        session.removeAttribute("code");
        //获取用户类型，根据用户类型去相应的表中 做用户和密码的校验
        Integer userType = logionForm.getUserType();
        //获取用户输入的用户名和密码
        String username=logionForm.getUsername();
        String password= MD5.encrypt(logionForm.getPassword());
        Map<String,Object> map =new LinkedHashMap<>();
        if(userType==1){
            Admin admin= adminService.selectAdminByUsernameAndpwd(username,password);
            //判断输入用户的用户名和密码是否存在数据库中
            if(admin!=null){
                //登录成功 后 需要根据用户id和用户类型生成token,并返回给浏览器
                String token=JwtHelper.createToken(admin.getId().longValue(),userType);
                map.put("token",token);
                //需要用户类型也返回给浏览器
                //map.put("userType",userType);
                return Result.ok(map);
            }
            return Result.fail().message("用户名或者密码有误");

        } else if (userType==2) {
            Student student= studentService.selectStudentByUsernameAndpwd(username,password);
            if(student!=null){
                String token=JwtHelper.createToken(student.getId().longValue(),userType);
                map.put("token",token);
                //map.put("userType",userType);
                return Result.ok(map);
            }
            return Result.fail().message("用户名或者密码有误");
        }else{
            Teacher teacher= teacherService.selectTeacherByUsernameAndpwd(username,password);
            Admin admin= adminService.selectAdminByUsernameAndpwd(username,password);
            if(teacher!=null){
                String token=JwtHelper.createToken(teacher.getId().longValue(),userType);
                map.put("token",token);
                //map.put("userType",userType);
                return Result.ok(map);
            }
            return Result.fail().message("用户名或者密码有误");
        }

    }

    @GetMapping("/getInfo")
    public Result<Object> getInfo(@RequestHeader("token")String token){

        //判断token是否有效
        if(JwtHelper.isExpiration(token)){
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }

        //解析token 获取用户id和用户类型 将用户类型返回给浏览器
        Long userId=JwtHelper.getUserId(token);
        Integer userType= JwtHelper.getUserType(token);
        Map<String,Object> map=new LinkedHashMap<>();
        map.put("userType",userType);
        if(userType==1){
            Admin admin=adminService.selectAdminById(userId);
            map.put("user",admin);
        }else if (userType==2){
            Student student=studentService.selectStudentById(userId);
            map.put("user",student);
        }else {
            Teacher teacher=teacherService.selectTeacherById(userId);
            map.put("user",teacher);
        }


        return Result.ok(map);
    }

    @PostMapping("/headerImgUpload")
    public Result<Object> headerImgUpload(@RequestPart("multipartFile")MultipartFile multipartFile /*HttpSession session*/) throws IOException {
        //先获取上传文件名称
        String originalFilename=multipartFile.getOriginalFilename();
        assert  originalFilename!=null;
        //获得文件格式（后缀）
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //为了避免保存服务端时文件名相同的冲突,可能会导致文件覆盖，所以使用UUId随机生成数
        String fileName=UUID.randomUUID().toString().toLowerCase().replace("-","").concat(suffix);
        //保存路径
        //ServletContext servletContext= session.getServletContext();
        //servletContext.getRealPath("/upload")
        String destPath="F:/All code/springboot/Smart_Campus/campus/src/main/resources/static/upload/".concat(fileName);
        //进行文件保存到服务端
        multipartFile.transferTo((new File(destPath)));
        return Result.ok("upload/".concat(fileName));
    }

    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result<Object> updatePwd(@PathVariable("oldPwd")String oldPwd,@PathVariable("newPwd")String newPwd,@RequestHeader("token")String token){

        //先判断token是否有效
        if(JwtHelper.isExpiration(token)){
            return Result.build(null,ResultCodeEnum.TOKEN_ERROR);
        }
        //先对用户输入的原密码进行加密
        oldPwd=MD5.encrypt(oldPwd);
        //解析token  获取用户id  根据id查询用户原密码输入是否正确
        Long userId =JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        assert userType != null;
        if(userType==1){
            Admin admin=adminService.selectAdminById(userId);
            if(!admin.getPassword().equals(oldPwd)){
                return Result.fail().message("原密码输入有误");
            }
            admin.setPassword(MD5.encrypt(newPwd));
            adminService.update(admin,new LambdaQueryWrapper<Admin>().eq(Admin::getId,userId));
        } else if (userType==2) {
            Student student =studentService.selectStudentById(userId);
            if(!student.getPassword().equals(oldPwd)){
                return Result.fail().message("原密码输入有误");
            }
            student.setPassword(MD5.encrypt(newPwd));
            studentService.update(student,new LambdaQueryWrapper<Student>().eq(Student::getId,userId));
        }else{
            Teacher teacher=teacherService.selectTeacherById(userId);
            if(!teacher.getPassword().equals(oldPwd)){
                return Result.fail().message("原密码输入有误");
            }
            teacher.setPassword(MD5.encrypt(newPwd));
            teacherService.update(teacher,new LambdaQueryWrapper<Teacher>().eq(Teacher ::getId,userId));
        }
        return Result.ok();
    }

}
